<?php
// +----------------------------------------------------------------------
// | XShop小程序商城
// +----------------------------------------------------------------------
// | Author: Peak Xin <xinyflove@gmail.com>
// +----------------------------------------------------------------------

namespace app\api\service;


use app\api\model\ThirdApp as ThirdAppModel;
use app\lib\exception\TokenException;

class AppToken extends Token{

    /**
     * 获取token
     * @param $ac
     * @param $se
     * @return string
     * @throws TokenException
     */
    public function get($ac, $se)
    {
        $app = ThirdAppModel::check($ac, $se);
        if (!$app)
        {
            throw new TokenException([
                'msg' => '授权失败',
                'errorCode' => 10004
            ]);
        }
        else
        {
            $scope = $app->scope;
            $uid = $app->id;
            $values = [
                'scope' => $scope,
                'uid' => $uid
            ];
            $token = $this->__saveToCache($values);
            return $token;
        }
    }

    /**
     * 保存登录信息到缓存，并获取token
     * @param $values
     * @return string
     * @throws TokenException
     */
    private function __saveToCache($values)
    {
        $token = self::generateToken();
        $expire_in = config('setting.token_expire_in');
        $result = cache($token, json_encode($values), $expire_in);
        if (!$result)
        {
            throw new TokenException([
                'msg' => '服务器缓存异常',
                'errorCode' => 10005
            ]);
        }
        return $token;
    }
}